package org.dreamwork.hyacinth.jasmine;

import org.dreamwork.hyacinth.HexAttachment;
import org.dreamwork.hyacinth.Mail;
import org.dreamwork.hyacinth.MailManager;
import org.dreamwork.hyacinth.MailType;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.web.controls.Page;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 将jasmine文件当做电子邮件的内容发送
 *
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-3-20
 * Time: 下午5:35
 */
public class HTMLMail extends Page {
    protected Mail mail = new Mail ();
    private List<IMailSendListener> listeners =
            Collections.synchronizedList (new ArrayList<IMailSendListener> ());

    public static final String MAIL_MANAGER_KEY = "com.swg.raychn.mail.HTMLMail.mail-manager";

    private static MailManager manager;

    public Mail getMail () {
        return mail;
    }

    public void addAttachment (String name, HexAttachment attachment) {
        mail.addAttachement (name, attachment);
    }

    public void addMailSendListener (IMailSendListener listener) {
        listeners.add (listener);
    }

    @Override
    public void onPagePreload (Page page) throws EventException {
        if (manager == null) {
            manager = (MailManager) application.getAttribute (MAIL_MANAGER_KEY);
        }
    }

    @Override
    public void render (PrintWriter writer) throws IOException, EventException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream ();
        PrintWriter pw = new PrintWriter (baos, true);
        super.render (pw);
        pw.flush ();

        mail.setType (MailType.Html);
        mail.setBody (baos.toString ());

        new Thread () {
            @Override
            public void run () {
                try {
                    manager.send (mail);
                    for (IMailSendListener msl : listeners)
                        msl.send (mail);
                } catch (Exception e) {
                    e.printStackTrace ();
                }
            }
        }.start ();
    }
}